package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @program: hm-dianping
 * @description: id生成器
 * @author: Feng
 * @create: 2023-03-09 08:31
 **/

@Component
public class IdWorker {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    private static final long TIME_OFFSET = 1672531200L;

    public Long nextId(String keyPrefix){
//        获取时间戳
        LocalDateTime now = LocalDateTime.now();
        long timeStamp = now.toEpochSecond(ZoneOffset.UTC) - TIME_OFFSET;
//        格式化
        String keyPrefix2 = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
//        String key = keyPrefix+keyPrefix2;
        //自增
//        加点前缀
        Long count = stringRedisTemplate.opsForValue().increment("incr:"+keyPrefix+":"+keyPrefix2);

        return (timeStamp<<32) | count;

    }

    public static void main(String[] args) {
//        获取时间并转换成秒
        System.out.println(LocalDateTime.of(2023,1,1,0,0).toEpochSecond(ZoneOffset.UTC));
    }
}
